package LeetCode;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}20:23
 */
public class LeetCode8 {

    public static void main(String[] args) {
        System.out.println(new LeetCode8().myAtoi("2147483648"));
        System.out.println(-1*(Integer.MAX_VALUE+1));
    }

    public int myAtoi(String str){
        if (str == null || str.length() == 0){
            return 0;
        }
        long result = 0;
        int i = 0;
        boolean isActive = false;
        while (str.charAt(i) == ' '){
            i++;
        }
        if (i >= str.length()){
            return 0;
        }
        if (str.length() == 0){
            return (int) result;
        }
        char[] arr = str.toCharArray();
        if (arr[i] == '-' || arr[i] == '+'){
            if (arr[i] == '-'){
                isActive = true;
            }
            i++;
        }else if (arr[i] > '9' || arr[i] < '0'){
            return (int) (isActive ? result*-1:result);
        }

        //下面就开始判断
        while (i < str.length()){
            int number = arr[i] - '0';
            if (number < 0 || number > 9){
                return (int) (isActive ? -1*result:result);
            }else {
                result = result * 10 + number;
            }

            if ( Math.abs(result) > Integer.MAX_VALUE)
                return isActive ? -1*Integer.MAX_VALUE-1:Integer.MAX_VALUE+1;

            i++;
        }

        return (int) (isActive ? -1*result : result);
    }
}
